package sk.tuke.constraintbuilder.analyzer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import net.sf.saxon.TransformerFactoryImpl;
import sk.tuke.constraintbuilder.utils.MyPreferences;

public class ISOSchematronValidator {

	public File validate(File schema, File input) throws FileNotFoundException, TransformerException{

		new File(MyPreferences.SCHEMATRON_TEMP_DIR).mkdir();
		File outputFile = new File(MyPreferences.SCHEMATRON_OUTPUT);
		
		//Copy iso_schematron_skeleton_for_saxon.xsl to user.dir
		InputStream inputStream = MyPreferences.class.getClassLoader().getResourceAsStream(MyPreferences.SCHEMATRON_SKELETON_XSL);
		File outFile = new File("iso_schematron_skeleton_for_saxon.xsl");
		OutputStream out = new FileOutputStream(outFile);
		int read = 0;
		byte[] bytes = new byte[1024];
		try {
			while ((read = inputStream.read(bytes)) != -1) {
				out.write(bytes, 0, read);
			}
			inputStream.close();
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("[ERROR] Copy iso_schematron_skeleton_for_saxon.xsl to user.dir");
		}

		//Validate
		try {	
			InputStream SvrlXSL_inputStream = MyPreferences.class.getClassLoader().getResourceAsStream(MyPreferences.SCHEMATRON_SVRL_XSL);
			File validatingXsl = new File(MyPreferences.SCHEMATRON_VALIDATING_XSL);
			TransformerFactory tfactory = TransformerFactoryImpl.newInstance();
			Transformer transformer = tfactory.newTransformer(new StreamSource(SvrlXSL_inputStream));
			transformer.transform(new StreamSource(schema), new StreamResult(validatingXsl));

			tfactory = TransformerFactoryImpl.newInstance();
			transformer = tfactory.newTransformer(new StreamSource(validatingXsl));
			transformer.transform(new StreamSource(input), new StreamResult(outputFile));
			SvrlXSL_inputStream.close();
		} catch (Exception ex) {
			System.out.println("EXCEPTION: " + ex);
			ex.printStackTrace();
		}
		return outputFile;
		
	}

}
